﻿/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import React, {Component} from 'react';
import {
	Alert,
	DeviceEventEmitter,
	FlatList,
	Image,
	Modal,
	RefreshControl,
	StyleSheet,
	TextInput,
	TouchableNativeFeedback,
	Text,View,ActivityIndicator
} from 'react-native';
import {Container} from 'native-base';
// import {Container,Text, View} from 'native-base';
import ScrollableTabView, {DefaultTabBar} from 'react-native-scrollable-tab-view';
import CostMasterDetail from './custInfo/CostMasterDetail';
import getStyles from '../style/styles';
import axiosInstance from './utils/request';

let rows=20;//
let totalPage=0;//总的页数
let itemNo=0;//item的个数
let styles={};

export default class CustInfoEditScene extends Component {

	constructor(props){
		super(props);
		this.state = {
			custCode:'',
			page:1,
			custName:'',
			custTypeName:'',
			bookName:'',
			tel:'',
			modalVisible: false,//模态场景是否可见
			isConnected: null,
			isLoading: true,//网络请求状态
			error: false,
			errorInfo: "",
			dataArray: [],
			showFoot:0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
			isRefreshing:false,//下拉控制
		}
	}

	//组件挂载完成后执行的方法
	componentDidMount(){
		const { params } = this.props.route;
		this.props.navigation.setOptions({
			title:params.custName,
		})
		this.listener = DeviceEventEmitter.addListener('Tab', ()=>this.selectTab(params));
		this.subscription = DeviceEventEmitter.addListener('Key', ()=>this.refreshData(params));
		this.setState(
		{
			custCode:params.custCode,
		},()=>{
				const params = {
					custCode:this.state.custCode,
					pageVO:{
						sort:'',
						order:''
					}
				};
				this.fetchCustInfo(params)
			}
		)
	}

	refreshData = (params) => {
		this.setState(
		{
			custCode:params.custCode,
		},()=>{
				const params = {
					custCode:this.state.custCode,
					pageVO:{
						sort:'',
						order:''
					}
				};
				this.fetchCustInfo(params)
			}
		)
	}

	selectTab(params){
		this.setState({
			custCode:params.custCode,
			},()=>{this.fetchCostHis()}
		)
	}

	componentWillUnmount() {
		this.subscription && this.subscription.remove();
		this.listener && this.listener.remove();
	};

	setModalVisible = (visible) => {
		this.setState({ modalVisible: visible });
	}

	//下载数据
	fetchCustInfo(data) {
		let url=global.server.url+'/custPrepay/selectCustCost';
		axiosInstance({
			method: 'post',
			url: url,
			data: data
		})
		.then(res => {
			let custInfoVo=res.custInfoVo;
			let arrears=res.arrears;
			this.setState({
				custCode:custInfoVo.custCode,
				custName:custInfoVo.custName,
				address:custInfoVo.address,
				custTypeName:custInfoVo.custTypeName,
				createTime:custInfoVo.createTime,
				money:custInfoVo.money,
				custStatusName:custInfoVo.custStatusName,
				tel:custInfoVo.tel,
				arrears:arrears
			});
		})
		.catch(err => {
			console.log('网络异常，请稍后再试！'+err);
		})
	}

	fetchCostHis() {
		let url=global.server.url+'/costHis/dataGrid';
		axiosInstance.post(url,
			{
				custCode:this.state.custCode,
				pageVO:{
					page:this.state.page,
					rows:rows
				}
			}).then(res => {
			let sumPayfees=0;
			let datas = [];
			let count=res.total;
			totalPage=res.pages;
			datas = datas.concat(res.records);
            let dataBlob = [];//这是创建该数组，目的放存在key值的数据，就不会报黄灯了
            let i = itemNo;
            datas.map(function (item) {
            	dataBlob.push({
                	key: i,
					payTime:item.payTime,
                    payfees: item.payfees,
                    payee: item.payee,
					payMode: item.payMode
                })
				sumPayfees+=item.payfees;
                i++;
            });
            itemNo = i;
            let foot = 0;
            if(this.state.page>=totalPage){
                foot = 1;//listView底部显示没有更多数据了
            }
            this.setState({
                //复制数据源
            	//  dataArray:this.state.dataArray.concat( responseData.results),
                dataArray:this.state.dataArray.concat(dataBlob),
                isLoading: false,
                showFoot:foot,
                isRefreshing:false,
				count:count,
				sumPayfees:sumPayfees.toFixed(2),
            });
            datas = null;//重置为空
            dataBlob = null;
		})
		.catch(error => {
        	this.setState({
				error: true,
                errorInfo: error
			});
			Alert.alert("网络异常，请稍后再试！");
        })
	}

	handleRefresh = () => {
        this.setState({
            page:1,
            isRefreshing:true,//tag,下拉刷新中，加载完全，就设置成flase
            dataArray:[]
        });
        this.fetchCostHis();
    }

	//加载等待页
    renderLoadingView() {
        return (
            <View style={styles.container}>
                <ActivityIndicator
                    animating={true}
                    color='blue'
                    size="large"
                />
            </View>
        );
    }

    _keyExtractor = (item, index) => index;

    //加载失败view
    renderErrorView() {
        return (
            <View style={styles.container}>
                <Text>
                    {this.state.errorInfo}
                </Text>
            </View>
        );
    }

	_separator(){
        return <View style={{height:1,backgroundColor:'#999999'}}/>;
    }

	_renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                    <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator />
                    <Text>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    _onEndReached(){
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot != 0 ){
            return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((this.state.page!=1) && (this.state.page>=totalPage)){
            return;
        } else {
            this.state.page++;
        }
        //底部显示正在加载更多数据
        this.setState({showFoot:2});
        //获取数据，在componentDidMount()已经请求过数据了
    	if (this.state.page>1){
            this.fetchCostHis();
        }
    }

	//渲染头部
	 _renderListHeader = (index) => {
         return(
            <View style={{alignItems:'center',flex:1}}>
				<Modal
					animationType={this.state.animationType}
					transparent={this.state.transparent}
					visible={this.state.modalVisible}
					onRequestClose={() => {
						this.setModalVisible(false)
					}}
				 >
				<View style={[styles.modalContainer,{backgroundColor: 'rgba(0, 0, 0, 0.5)'}]}>
					<View style={[styles.innerContainer,{backgroundColor: '#F0F8FF', padding: 20}]}>
						<View style={styles.row}>
							<View >
								<Text style={styles.tips}>请输入一个或多个条件</Text>
							</View>
							<TextInput
								style={styles.textInput}
								placeholder={'用户名称'}
								onChangeText={(text) => {
									this.custName = text;
									this.setState({custName: text})
								}}
								//输入框下划线
								underlineColorAndroid={'transparent'}/>
							<TextInput
								style={styles.textInput}
								placeholder={'用户编号'}
								onChangeText={(text) => {
									this.custCode = text;
									this.setState({custCode: text})
								}}
								//输入框下划线
								underlineColorAndroid={'transparent'}/>
							<TextInput
								style={styles.textInput}
								placeholder={'用户地址'}
								onChangeText={(text) => {
									this.address = text;
									this.setState({address: text})
							 }}
							 	//输入框下划线
								 underlineColorAndroid={'transparent'}/>
						</View>
						<View style={styles.settingStyle}>
							<Text
								onPress={this.searchData.bind(this,index)}
								style={{fontSize:20,marginTop:10}}>
								确定
							</Text>
							<Text
								onPress={this.setModalVisible.bind(this,false) }
								style={{fontSize:20,marginTop:10}}>
								关闭
							</Text>
						</View>
						</View>
					</View>
				</Modal>
      		</View>
        )
    }

	searchData(index){

	}

    render() {
		styles=getStyles();
		const { params } = this.props.route;
        return (

				<ScrollableTabView
					style={style.container}
					tabBarUnderlineStyle={{backgroundColor:'#000000', height:1}}
					renderTabBar={()=><DefaultTabBar backgroundColor='rgba(135, 206 ,235, 0.5)' />}
					tabBarPosition='bottom'
					initialPage={params.tabIndex}
					onChangeTab={
						(obj) => {
							if(obj.i==0){
								this.fetchCustInfo();
							}else if(obj.i==1){
								//此处将dataArray设置为空，是防止Tab切换时dataArray的元素累加
								this.setState(
								{
									dataArray: [],
								},()=>{
										this.fetchCostHis()
									}
								)
							}
						}
					}
				>
					<View style={style.container} tabLabel="基本信息">
						<View style={styles.items}>
							<Text style={styles.textStyle}>客户编号：</Text>
							<Text style={styles.textStyle}>{this.state.custCode}</Text>
						</View>
						<View style={styles.items}>
							<Text style={styles.textStyle}>客户名称：</Text>
							<Text style={styles.textStyle}>{this.state.custName}</Text>
							<TouchableNativeFeedback activeOpacity={0.5}  onPress={() => {
									this.props.navigation.navigate('CustInfoEdit', {name:'客户名称',value:this.state.custName,custCode:this.state.custCode})
								}}>
								<Image style={{width:20,height:20,position:'absolute',right:6}} source={require('../img/arrow04.png')} />
							</TouchableNativeFeedback>
						</View>
						<View style={styles.items}>
							<Text style={styles.textStyle}>用户类型：</Text>
							<Text style={styles.textStyle}>{this.state.custTypeName}</Text>
						</View>
						<View style={styles.items}>
							<Text style={styles.textStyle}>开户时间：</Text>
							<Text style={styles.textStyle}>{this.state.createTime}</Text>
						</View>
						<View style={styles.items}>
							<Text style={styles.textStyle}>当前余额：</Text>
							<Text style={styles.textStyle}>{this.state.money}</Text>
						</View>
						<View style={styles.items}>
							<Text style={styles.textStyle}>欠费金额：</Text>
							<Text style={styles.textStyle}>{this.state.arrears}</Text>
						</View>
						<View style={styles.items}>
							<Text style={styles.textStyle}>详细地址：</Text>
							<Text style={styles.textStyle}>{this.state.address}</Text>
							<TouchableNativeFeedback activeOpacity={0.5}  onPress={() => {
									this.props.navigation.navigate('CustInfoEdit', {name:'详细地址',value:this.state.address,custCode:this.state.custCode})
								}}>
								<Image style={{width:20,height:20,position:'absolute',right:6}} source={require('../img/arrow04.png')} />
							</TouchableNativeFeedback>
						</View>
						<View style={styles.items}>
							<Text style={styles.textStyle}>联系电话：</Text>
							<Text style={styles.textStyle}>{this.state.tel}</Text>
							<TouchableNativeFeedback activeOpacity={0.5}  onPress={() => {
									this.props.navigation.navigate('CustInfoEdit', {name:'联系电话',value:this.state.tel,custCode:this.state.custCode})
								}}>
								<Image style={{width:20,height:20,position:'absolute',right:6}} source={require('../img/arrow04.png')} />
							</TouchableNativeFeedback>
						</View>
						<View style={styles.items}>
							<Text style={styles.textStyle}>用户状态：</Text>
							<Text style={styles.textStyle}>{this.state.custStatusName}</Text>
						</View>
					</View>
					<View style={style.container} tabLabel ="缴费记录">
						<View style={{
							height:40,
							flexDirection:'row',
							alignItems:'center',
							borderBottomWidth:1,
							borderBottomColor:'#D7D7D7',
							backgroundColor:"#F5FCFF",
							paddingLeft:6
							}}>
							<View style={styles.flex}>
								<Text style={style.headerText}>缴费笔数：{this.state.count}</Text>
							</View>
							<View style={styles.flex }>
								<Text style={style.headerText}>缴费总额：{this.state.sumPayfees}</Text>
							</View>
						</View>
						<FlatList
							data = {this.state.dataArray}
							renderItem = {({item}) =>
								<TouchableNativeFeedback
									onPress = {() => {

									}}>
									<View style={style.textMainStyle}>
										<Text style={styles.margin}>缴费时间：{item.payTime}</Text>
										<Text style={styles.margin}>缴费金额：{item.payfees}元</Text>
										<Text style={styles.margin}>收款人员：{item.payee}</Text>
										<Text style={styles.margin}>支付方式：{item.payMode}</Text>
									</View>
								</TouchableNativeFeedback>
							}
							ListFooterComponent={this._renderFooter.bind(this)}
							onEndReached={this._onEndReached.bind(this)}
							onEndReachedThreshold={0.1}
							keyExtractor={this._keyExtractor}
							ListHeaderComponent={this._renderListHeader(1)}
							//为刷新设置颜色
							refreshControl={
								<RefreshControl
									refreshing={this.state.isRefreshing}
									onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
									colors={['#ff0000', '#00ff00','#0000ff','#3ad564']}
									progressBackgroundColor="#ffffff"
								/>
							}
						/>
					</View>

					<View style={style.container} tabLabel ="用水记录">
						<CostMasterDetail custCode={params.custCode} navigation={this.props.navigation}/>
					</View>
				</ScrollableTabView>

		)
    }
}

const style = StyleSheet.create({
    container: {
        flex: 1,
		flexDirection: 'column',
        backgroundColor: 'white'
    },
  	flex:{
    	flex:1
  	},
    headerText: {
        fontSize: 15,
        textAlign: 'left',
        margin: 5
    },
	textMainStyle: {
        flex: 1,
        backgroundColor: 'white',
        padding: 10,
        paddingVertical:10,
        marginLeft: 5,
        marginRight: 5,
        marginVertical: 3,
        borderColor: '#dddddd',
        borderStyle: null,
        borderWidth: 0.5,
        borderRadius: 2,
        shadowColor: 'gray',    // 设置阴影
        shadowOffset: {width:0.5, height: 0.5},
        shadowOpacity: 0.4,   // 透明度
        shadowRadius: 1,
        elevation:2   //   高度，设置Z轴，可以产生立体效果
   },
});
